<template>
  <base-modal :title="$t('product.component.editContactDialog.addContact')" :show.sync="addContactDialog" width="600px" class="edit-contact-dialog" @closed="reset">
    <form class="edit-contact-form-container" v-if="init">
      <form-builder :fields="fields" class="edit-contact-form" ref="form" :value="form" @update="update">

        <template slot="phone" slot-scope="{field}">
          <form-item :label="field.displayName" :validation="validation" :form="form">
            <form-text
              :field="field"
              :value="form.phone" @update="update"
              :placeholder="field.placeholder"/>
          </form-item>
        </template>

      </form-builder>
    </form>
    <div class="dialog-footer" slot="footer">
      <el-button @click="addContactDialog = false">{{$t('common.base.cancel')}}</el-button>
      <el-button @click="submit" type="primary" :disabled="pending">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>
</template>

<script>
import * as FormUtil from '@src/component/form/util';
import * as LinkmanApi from '@src/api/LinkmanApi'
import { getProductList } from '@src/api/ProductApi'
import {createRemoteValidate} from '@src/util/validator'

export default {
  name: 'edit-contact-dialog',
  props: {
    customer: {
      type: Object,
      default: () => ({}),
    },
    product: {
      type: Object,
      default: () => ({}),
    },
    originalValue: {
      type: Object,
      default: () => ({}),
    },
    isPhoneUnique: Boolean
  },
  data() {
    return {
      init: false,
      addContactDialog: false,
      pending: false,
      products: [],
      addresses: [],
      form: {
        name: null,
        remark: '',
        sex: '',
        position: '',
        department: '',
        address: '', // address的ID
        customId: '',
        customer: {},
        id: '',
        phone: null,
        email: null,
        productId: [], // 数组，包含产品对象
      },
      loadData: false,
      validation: this.isPhoneUnique ? (...rest) => {
        let value = rest[0]
        // 原先电话必填，现在存在非必填的情况，如果没填电话，此处不做是否存在相同号码的校验，否则接口会返回已存在
        if (!value) return null
        let fn = createRemoteValidate(LinkmanApi.checkUnique4Phone, (value, field) => {
          return {
            id: this.originalValue.id || '',
            phone: value
          }
        })
        return fn(...rest)
      } : true
    }
  },
  computed: {
    customerId() {
      return (this.customer && this.customer.id) || '';
    },
    fields() {
      let fields = [{
        formType: 'text',
        fieldName: 'name',
        displayName: this.$t('common.base.contact'),
        placeholder: this.$t('product.component.editContactDialog.placeholder.name'),
        isNull: 0,
      }, {
        formType: 'phone',
        fieldName: 'phone',
        displayName: this.$t('common.base.phone'),
        placeholder: this.$t('product.component.editContactDialog.placeholder.phone'),
        isNull: 1,
      }, {
        formType: 'select',
        fieldName: 'sex',
        displayName: this.$t('common.fields.sex.displayName'),
        placeholder: this.$t('common.placeholder.select'),
        isNull: 1,
        setting: {
          dataSource: [this.$t('common.fields.sex.options.man'), this.$t('common.fields.sex.options.woman')],
        }
      }, {
        formType: 'email',
        fieldName: 'email',
        displayName: this.$t('common.fields.email.displayName'),
        placeholder: this.$t('product.component.editContactDialog.placeholder.email'),
        isNull: 1,
      }, {
        formType: 'text',
        fieldName: 'position',
        displayName: this.$t('common.fields.position.displayName'),
        placeholder: '',
        isNull: 1,
      }, {
        formType: 'text',
        fieldName: 'department',
        displayName: this.$t('common.fields.department.displayName'),
        placeholder: '',
        isNull: 1,
      }, {
        formType: 'textarea',
        fieldName: 'remark',
        displayName: this.$t('common.fields.remark.displayName'),
        placeholder: this.$t('product.component.editContactDialog.placeholder.remark'),
        isNull: 1,
      }, {
        formType: 'select',
        fieldName: 'address',
        displayName: this.$t('common.fields.relationAddress.displayName'),
        placeholder: this.$t('common.placeholder.select'),
        isNull: 1,
        setting: {
          dataSource: this.addresses || [],
        }
      }]
      fields.forEach(f => {
        if (['phone', 'email'].includes(f.fieldName)) {
          f.isNullRelationFields = fields.filter(field => 
            ['phone', 'email'].includes(field.fieldName)
          )
        }
      })
      return fields
    },
    address () {
      let address = this.customer.customerAddress ? (this.customer.customerAddress.adProvince || '') + (this.customer.customerAddress.adCity || '') + (this.customer.customerAddress.adDist || '') + (this.customer.customerAddress.adAddress || '') : '';
      return address;
    }
  },
  methods: {
    genPlaceholder(field){
      return FormUtil.genPlaceholder(field);
    },
    async submit() {
      try {
        const validateRes = await this.$refs.form.validate();
        if (!validateRes) return;

        this.pending = true;

        const params = {
          ...this.form,
          customer: this.customer,
          productId: this.products
            .filter(p => this.form.productId.some((pId => pId === p.value)))
            .map(p => ({
              id: p.value,
              name: p.text,
            })),
        };
        // 存在重复校验且值为空字符时，接口会提示重复，通过值为null可以避免
        if(!params.phone) {
          params.phone = null
        }

        let result = await this.$http.post('/linkman/createByJson', params);

        if(result.status != 0) {
          this.pending = false;
          return this.$platform.notification({
            title: this.$t('common.base.fail'),
            message: result.message || this.$t('product.tips.createError'),
            type: 'error',
          });
        }

        this.pending = false;
        this.addContactDialog = false;
        let linkman = [
          {
            label: this.form.name,
            value: result.data,
            phone: this.form.phone
          }
        ]
        this.$emit('updateLinkman', linkman);
        this.reset();
        this.$eventBus.$emit('customer_contact_table.update_linkman_list');
        this.$eventBus.$emit('customer_info_record.update_record_list');
        this.$eventBus.$emit('customer_detail_view.update_statistical_data');
        this.$eventBus.$emit('customer_detail_view.update_customer_detail');

      } catch (e) {
        this.pending = false;
        console.error('addContactDialog submit catch e', e);
      }
    },
    reset() {
      this.form = {
        name: null,
        remark: '',
        sex: '',
        position: '',
        department: '',
        address: '',
        customId: '',
        customer: {},
        id: '',
        phone: null,
        email: null,
        productId: [],
      };
      this.init = false;
    },
    update({field, newValue, oldValue}) {
      let {fieldName, displayName} = field;
      // 手机号去空格
      if(fieldName == 'phone') {
        newValue = newValue.trim()
      }
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }
      this.$set(this.form, fieldName, newValue)
    },
    openDialog() {
      this.addContactDialog = true;
      this.fetchAddress();
      // 没有关联产品，去除调用，如果之后需要添加，因数量较大，务必使用分页组件~
      // this.fetchProducts();
      this.init = true;
    },
    fetchAddress() {
      return this.$http.get('/customer/address/list', {
        customerId: this.customer.id,
        pageSize: 100000,
        pageNum: 1,
      })
        .then(res => {
          this.addresses = res.list
            .map(p => ({
              text: p.province + p.city + p.dist + p.address,
              value: p.id,
            }));

          // 把被删除的地址过滤掉
          const address = this.originalValue.address;
          if (address && this.addresses.some(a => a.value === address)) {
            this.form.address = address;
          }

          return this.addresses;
        })
        .catch(err => console.error('fetchAddress catch err', err));
    },
    fetchProducts() {
      return getProductList({
        customerId: this.customer.id,
        pageSize: 100000,
        pageNum: 1,
      })
        .then(res => {
          this.products = res.list
            .map(p => ({
              text: p.name,
              value: p.id,
            }));
          // 把被删除的产品过滤掉
          const productId = this.originalValue.productId;
          if (productId && productId.length) {
            this.form.productId = productId.map(p => p.id)
              .filter(pId => this.products.some(p => p.value === pId));
          }

          return this.products;
        })
        .catch(err => console.error('fetchProducts catch err', err));
    }
  },
}
</script>

<style lang="scss">

  .edit-contact-dialog {
    .base-modal-body {
      padding: 15px 30px 0;
    }


    .edit-contact-form-container {
      width: 100%;
      margin: 0 auto;

      .edit-contact-form {
        padding: 10px 0 5px;
      }

      .form-item label {
        /*text-align: right;*/
        width: 80px;
      }

      .form-builder {
        width: 100%;
      }

      .form-item-control {
        // max-width: calc(100% - 80px);
      }
    }

    .dialog-footer {
      text-align: right;
      padding: 0px 0px 15px;
    }
  }

</style>
